import logger from './logger';
import common from '@ohos.app.ability.common';
import preferences from '@ohos.data.preferences';

export default class db {
  private context: common.Context;
  private static _instance: db;

  public static get instance(): db {
    return this._instance;
  }

  public static createInstance(context: common.Context): db {
    if (this._instance == null)
      this._instance = new db(context);
    return this._instance;
  }

  private constructor(context: common.Context) {
    this.context = context;
  }

  query(key: string): Promise<preferences.ValueType> {
    return new Promise((resolve) => {
      try {
        preferences.getPreferences(this.context, 'db').then((preferences) => {
          preferences.get(key, '').then((value) => resolve(value)).catch((err) => {
            logger.error(err);
            resolve('');
          });
        }).catch((err) => {
          logger.error(err);
          resolve('');
        });
      } catch (e) {
        logger.error(e);
        resolve('');
      }
    });
  }

  update(key: string, value: preferences.ValueType): Promise<void> {
    return new Promise((resolve) => {
      try {
        preferences.getPreferences(this.context, 'db').then((preferences) => {
          preferences.put(key, value);
          preferences.flush();
          resolve();
        }).catch((err) => {
          logger.error(err);
          resolve();
        });
      } catch (e) {
        logger.error(e);
        resolve();
      }
    });
  }

  async clear() {
    await this.update('user_id', '');
    await this.update('expires_in', '');
    await this.update('access_key', '');
    await this.update('refresh_token', '');
    await this.update('user_name', '');
    await this.update('user_face', '');
  }
}